﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
using zhangmenren.IService;
using System.Text.RegularExpressions;
using zhangmenren.Models;
using System.Net;
using zhangmenren.Untils;
using Cookie = zhangmenren.Untils.Cookie;
using Microsoft.AspNetCore.Rewrite.Internal.UrlActions;
using zhangmenren.Models.help;
using zhangmenren.Models.Enums;

namespace zhangmenren.Controllers
{
    public class TuiJianController : Controller
    {
        private IWorksService worksService;

        private IChapterService chapterService;
        private ICensusService censusService;
        private ICacheService cacheService;
        private ICommentServic commentServic;
        private IUserService userService;
        private IBannerService bannerService;
        public TuiJianController(IBannerService _bannerService, IUserService _userService,IWorksService _worksService, IChapterService _chapterService, ICensusService _censusService, ICacheService _cacheService, ICommentServic _commentServic)
        {
            worksService = _worksService;
            chapterService = _chapterService;
            censusService = _censusService;
            cacheService = _cacheService;
            commentServic = _commentServic;
            userService = _userService;
            bannerService = _bannerService;

        }
        // GET: /<controller>/
        public async Task<IActionResult> Index()
        {
            ViewBag.ZMRID = 0;
            var user = QTCookie.GetCookie<UserCook>(HttpContext);
            if (user != null)
            {
                var entity = await userService.FindById(user.Id);

                ViewBag.ZMRID = entity.ZMRID;
            }


            var list = await worksService.Selelct(WorkType.XKSP,"");
            return View(list?.ToList());
        }

        public async Task<IActionResult> JingPinKC(int id=0)
        {
            if (id==0)
            {
                var ret = await worksService.Selelct(WorkType.JPKC,"");
                if (ret.Any())
                {
                    var chaps = await chapterService.Selelct(ret.FirstOrDefault().Id);
                    ViewBag.Ca = chaps;
                    var comments = await commentServic.FindByWorkId(ret.FirstOrDefault().Id);
                    ViewBag.Comment = comments;
                    var user = QTCookie.GetCookie<UserCook>(HttpContext);
                    ViewBag.ISOK = false;
                    ViewBag.Ulr = chaps.ToList().Count > 0 ? chaps.ToList()[0].Url : "";

                    if (ret?.FirstOrDefault()?.AuthorId>0)
                    {
                        ViewBag.zuozhe = await userService.FindByZMRID(ret.FirstOrDefault().AuthorId);
                        var chushou = await worksService.FindByZMId(ret.FirstOrDefault().AuthorId);
                        ViewBag.zaisou = chushou.Count();
                    }
                    

                    if (user == null)
                    {
                        return View(ret.FirstOrDefault());
                    }


                    

                    var census = await censusService.FindByUserId(user.Id);
                    var num = census.ToList().FindAll(p => p.Type == 3 && p.WorkId == id)?.Count ?? 0;
                    if (num > 0)
                    {
                        ViewBag.ISOK = true;

                    }
                }
            }
            else
            {
                var result = await worksService.FindById(id);

                var chaps = await chapterService.Selelct(id);
                ViewBag.Ca = chaps;
                var comments = await commentServic.FindByWorkId(id);
                ViewBag.Comment = comments;
                var user = QTCookie.GetCookie<UserCook>(HttpContext);
                ViewBag.ISOK = false;
                ViewBag.Ulr = chaps.ToList().Count > 0 ? chaps.ToList()[0].Url : "";
                if (user == null)
                {
                    return View(result);
                }
                var census = await censusService.FindByUserId(user.Id);
                var num = census.ToList().FindAll(p => p.Type == 3 && p.WorkId == id)?.Count ?? 0;
                if (num > 0)
                {
                    ViewBag.ISOK = true;

                }

                return View(result);
            }
            return View();

        }


        public async Task<IActionResult> TuiJian()
        {

            ViewBag.Banner = await GetData.GetBanner(bannerService, cacheService, "TuiJianTuiJian", BannerType.ZMTJ);
            var list = await worksService.Selelct(WorkType.ZMTJ, "");
            return View(list?.ToList());
        }

        public async Task<IActionResult> Detail(int id)
        {
            var list = await chapterService.FindByWork(id);
            var comments = await commentServic.FindByWorkId(id);
            ViewBag.Comment = comments.ToList();
            ViewBag.ISOK = false;
            var user = QTCookie.GetCookie<UserCook>(HttpContext);
            if (user == null)
            {
                return View(list.FirstOrDefault());
            }

            var census = await censusService.FindByUserId(user.Id);
            var num = census.ToList().FindAll(p => p.Type == 3 && p.WorkId == id)?.Count??0;
            if (num>0)
            {
                ViewBag.ISOK = true;
                
            }
            return View(list.FirstOrDefault());
        }

        /// <summary>
        /// 添加收藏关注
        /// </summary>
        /// <returns>The one.</returns>
        /// <param name="id">Identifier.</param>
        [HttpPost]
        public async Task<JsonResult> AddOne(int workId ,int type)
        {
            if (workId != 0)
            {
                var user = QTCookie.GetCookie<UserCook>(HttpContext);
                if (user==null)
                {
                    return Json(new { state = "fail", msg = "请先登录" });
                }
                CensusEntity entity = new CensusEntity();
                entity.Type = type;
                entity.WorkId = workId;
                entity.UserId = user.Id;
                var result = await censusService.Add(entity);
                if (type==1)
                {
                    return Json(new { state = "ok", msg = "点赞成功" });
                }
                if (type == 1)
                {
                    return Json(new { state = "ok", msg = "关注成功" });
                }
                return Json(new { state = "ok", msg = "成功" });
            }
            return Json(new { state = "fail", msg = "标识错误" });
        }

        /// <summary>
        /// 获取收藏和关注状态
        /// </summary>
        /// <returns>The one.</returns>
        /// <param name="id">Identifier.</param>
        [HttpPost]
        public async Task<JsonResult> GetOne(int workId = 0)
        {
            int sta = 0;

            var user = QTCookie.GetCookie<UserCook>(HttpContext);
            if (user==null)
            {
                return Json(new { state = "fail", msg = "请先登录" });
            }
            int userId = QTCookie.GetCookie<UserCook>(HttpContext).Id;
            if (workId != 0)
            {
            
                var list = await censusService.FindByWorkId(workId);
               var  ls = list.ToList().FindAll(p => p.UserId == userId);
                if (ls.FindAll(p=>p.Type==1)?.Count>0)
                {
                    sta = 1;
                }
                if (ls.FindAll(p => p.Type == 2)?.Count > 0)
                {
                    sta += 2;
                }
                return Json(new { state = sta, msg = "查询成功" });
            }
            return Json(new { state = sta, msg = "标识错误" });
        }

        [HttpPost]
        public async Task<JsonResult> Search(string key)
        {
            var result = await worksService.Selelct(1, 50, key);
            var list = result.ToList().FindAll(p => p.Type == WorkType.ZMTJ);
            return Json(new { data = list, state = "ok", msg = "查询成功" });
        }

        [HttpPost]
        public async Task<JsonResult> AddComment(int workId,string content)
        {
            var user = QTCookie.GetCookie<UserCook>(HttpContext);
            if (user == null)
            {
                return Json(new { state = "fail", msg = "请先登录" });
            }

            if (workId != 0)
            {
                CommentEntity entity = new CommentEntity();
                entity.HeadImg = user.Head;
                entity.Content = content;
                entity.UserName = user.UserName;
                entity.WorkId = workId;
                var result = await commentServic.Add(entity);

                return Json(new { state = "ok", msg = "评论成功" });
            }
            return Json(new { state = "faile", msg = "标识错误" });
        }

    }
}
